package com.pro.addresslist.ui.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Network;
import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.bll.FriendshipBLL;
import com.pro.addresslist.dal.bll.RelationshipBLL;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.dal.model.Friendship;
import com.pro.addresslist.dal.model.V_FriendBean;
import com.pro.addresslist.sqllite.ContactInfoServise;
import com.pro.addresslist.tools.NetUtil;
import com.pro.addresslist.tools.constantUtil;
import com.pro.addresslist.ui.activity.ContactsActivity.ReceiveBroadCast;
import com.pro.addresslist.ui.activity.ContactsActivity.myThreadFriend;
import com.pro.addresslist.ui.adapter.CommonAdapter;
import com.pro.addresslist.ui.adapter.PinnedHeaderExpandableAdapter;
import com.pro.addresslist.ui.adapter.ViewHolder;
import com.pro.addresslist.ui.common.BaseActivity;
import com.pro.addresslist.ui.common.MyApplication;
import com.pro.addresslist.ui.view.PinnedHeaderExpandableListView;
import com.pro.addresslist.ui.view.PopMenu;

public class PersonalInformationActivity extends BaseActivity {
	ContactInfo list = new ContactInfo();
	String phonnumbers;
	String friend;
	ContactInfo contactInfo = new ContactInfo();
	List<String> phone = new ArrayList<String>();
	List<V_FriendBean> friends = new ArrayList<V_FriendBean>();//  联系人朋友
	TextView head_img;// 姓
	TextView contact_name;// 姓名
	// TextView txt_gender;//性别
	TextView txt_national;// 民族
	TextView txt_birthday;// 生日
	TextView txt_work_address;// 单位地址
	TextView txt_hobby;// 兴趣爱好
	TextView txt_preferfoods;// 饮食偏好
	TextView txt_work_phone;// 单位电话
	TextView txt_home_address;// 家庭地址
	TextView txt_family_phone;// 家庭电话
	TextView txt_other_phone;// 其他电话
	TextView txt_department;// 职务
	TextView txt_tv_Depict;// 备注
	TextView txt_address;// 地域
	TextView txt_focal;// 归口

	ListView phonenumber;
	CommonAdapter<String> contactPhone;
	private String Lid, contactID, friendId;
	List<V_FriendBean> listfriends;// 联系人朋友
	/* mt朋友列表展示 */
	private PinnedHeaderExpandableListView explistview;
	private List<List<String>> childrenData;
	private List<String> groupData;
	private int expandFlag = -1;// 控制列表的展开
	private PinnedHeaderExpandableAdapter adapter;
	private Button add_friends;// 添加朋友

	// private List<V_FriendBean> childlist = new ArrayList<V_FriendBean>();
	private List<Object[]> listitm = new ArrayList<Object[]>();
	private PopMenu pop;
	private static final int ITEM_DELETE = 1;
	private int postion=-1;

	@Override
	public int getLayout() {
		return R.layout.activity_personal_information;
	}

	void init() {
		phonenumber = (ListView) findViewById(R.id.lv_phone);
		add_friends = (Button) findViewById(R.id.add_friends);// 添加朋友

		head_img = (TextView) findViewById(R.id.head_Img);
		contact_name = (TextView) findViewById(R.id.txt_contactname);
		txt_national = (TextView) findViewById(R.id.txt_national);// 民族
		txt_birthday = (TextView) findViewById(R.id.txt_birthday);// 生日
		txt_work_address = (TextView) findViewById(R.id.txt_work_address);// 单位地址
		txt_hobby = (TextView) findViewById(R.id.txt_hobby);// 兴趣爱好
		txt_preferfoods = (TextView) findViewById(R.id.txt_preferfoods);// 饮食偏好
		txt_work_phone = (TextView) findViewById(R.id.work_phone);// 单位电话
		txt_home_address = (TextView) findViewById(R.id.txt_home_address);// 家庭地址
		txt_family_phone = (TextView) findViewById(R.id.family_phone);// 家庭电话
		txt_other_phone = (TextView) findViewById(R.id.other_phone);// 其他电话
		txt_department = (TextView) findViewById(R.id.txt_department);// 职务
		txt_tv_Depict = (TextView) findViewById(R.id.tv_Depict);// 备注
		txt_address = (TextView) findViewById(R.id.txt_address);// 地域
		txt_focal = (TextView) findViewById(R.id.txt_focal);// 归口
		explistview = (PinnedHeaderExpandableListView) findViewById(R.id.explistview);// 朋友列表
	}

	void initclick() {
		add_friends.setOnClickListener(this);
	}

	void initData() {
		// groupData.add(i, list.get(i).get_Name());
		groupData = new ArrayList<String>();
		childrenData = new ArrayList<List<String>>();

		// 设置悬浮头部VIEW
		explistview.setHeaderView(getLayoutInflater().inflate(
				R.layout.group_head, explistview, false));

		adapter = new PinnedHeaderExpandableAdapter(childrenData, groupData,
				getApplicationContext(), explistview);
		explistview.setAdapter(adapter);

		// 设置子项点击事件
		explistview.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				/*
				 * Toast.makeText( PersonalInformationActivity.this, "你点击了" +
				 * adapter.getChild(groupPosition, childPosition),
				 * Toast.LENGTH_SHORT).show();
				 */

				friendId = listfriends.get(childPosition).get_ContactID();
				// 朋友id
				new Thread(new SelectIdByContactId()).start();
				return false;
			}
		});

		// 设置长按时的事件
		registerForContextMenu(explistview);
	}

	// 长按出现的菜单
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, ITEM_DELETE, 1, "删除");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item
				.getMenuInfo();

		int type = ExpandableListView
				.getPackedPositionType(info.packedPosition);
		// 子条目
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			String childId = ((TextView) info.targetView
					.findViewById(R.id.childid)).getText().toString().trim();
			postion=(int) info.packedPosition;
			switch (item.getItemId()) {
			case ITEM_DELETE:
				//Toast.makeText(this, "删除" + childId, Toast.LENGTH_SHORT).show();
				FriendshipBLL.DeleteFriendShip(getApplicationContext(), childId);
				break;
			default:
				return false;
			}
			return true;
			// 组
		}

		return true;
	}

	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case constantUtil.Num_SelectContactByID:
				/**
				 * 这里边是刷新的一系列数据准备，准备好后进行刷新
				 **/
				List<ContactInfoBySqlite> listcons = (List<ContactInfoBySqlite>) msg.obj;

				Drawable img_female,
				img_male;
				Resources res = getResources();
				img_female = res.getDrawable(R.drawable.female);
				img_male = res.getDrawable(R.drawable.male);
				// 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
				img_female.setBounds(0, 0, img_female.getMinimumWidth(),
						img_female.getMinimumHeight());
				img_male.setBounds(0, 0, img_male.getMinimumWidth(),
						img_male.getMinimumHeight());

				if (listcons.size() != 0) {
					for (ContactInfoBySqlite con : listcons) {
						// 联系人
						contactID = con.get_ContactID();
						groupData.add(0, con.get_Name());
						head_img.setText(con.get_Name().substring(0, 1));
						contact_name.setText(con.get_Name());
						txt_department.setText(con.get_Department());// 职务
						// 性别
						if (con.get_Sex() == 0) {

							contact_name.setCompoundDrawables(null, null,
									img_male, null); // 设置左图标

						} else {
							contact_name.setCompoundDrawables(null, null,
									img_female, null); // 设置左图标
						}
						txt_national.setText(con.get_Nationality());// 民族
						txt_birthday.setText(con.get_Birthday());// 生日
						txt_work_address.setText(con.get_DepartAddress());// 单位地址
						txt_hobby.setText(con.get_Interest());// 兴趣爱好
						txt_preferfoods.setText(con.get_Food());// 饮食偏好
						txt_work_phone.setText(con.get_DepartTell());// 单位电话
						txt_home_address.setText(con.get_Address());// 家庭地址
						txt_family_phone.setText(con.get_FamilyTell());// 家庭电话
						txt_other_phone.setText(con.get_OtherTell());// 其他电话
						txt_department.setText(con.get_Department());// 职务
						txt_tv_Depict.setText(con.get_Depict());// 备注
						txt_address.setText(con.get_dy());// 地域
						txt_focal.setText(con.get_gk());// 归口
						phonnumbers = con.get_MobileEn();

						String[] sourceStrArray = phonnumbers.split(",");// 用，分隔字符串
																			// //
																			// 取出单个电话号码
						phone.clear();
						for (int i = 0; i < sourceStrArray.length; i++) {

							phone.add(sourceStrArray[i]);

						}
						contactPhone.notifyDataSetChanged();
					}

				}
				Log.i("libs", "shu" + listcons.size());
				FriendshipBLL.SelectFriendShipViewmt(mContext, contactID,
						mHandler);
				adapter.notifyDataSetChanged();
				break;
			case constantUtil.Num_SelectFriendByContactId:
				if(childrenData.size()!=0){
					childrenData.clear();
				}
				listfriends = (List<V_FriendBean>) msg.obj;
				if (listfriends.size() != 0) {
					List<String> item = new ArrayList<String>();
					for (V_FriendBean con : listfriends) {
						item.add(con.get_ContactID() + "," + con.get_Name());
						;
					}
					childrenData.add(item);
					adapter.notifyDataSetChanged();
				}
				break;
			case constantUtil.Num_SelectIdByContactId:
				String id = (String) msg.obj;
				if (id != null) {
					Intent intent = new Intent(
							PersonalInformationActivity.this,
							PersonalInformationActivity.class);
					intent.putExtra("contactID", id);
					startActivity(intent);
					PersonalInformationActivity.this.finish();
				}
				break;
			case constantUtil.Num_SelectCountByState:
				int state = msg.arg1;
				if (state > 0) {
					// 有更改
					Builder dia = new AlertDialog.Builder(
							PersonalInformationActivity.this)
							.setMessage("本地有修改，是否前往上传页面？")
							.setPositiveButton(
									"是",
									new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											Intent intent = new Intent(
													PersonalInformationActivity.this,
													SynchronizeActivity.class);
											startActivity(intent);

										}
									})
							.setNegativeButton(
									"否",
									new android.content.DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

										}
									});
					dia.show();

				} else {
					Intent intent = new Intent();
					intent.putExtra("ContactId", contactID);
					intent.putExtra("action", "friends");
					intent.setClass(PersonalInformationActivity.this,
							ContactsActivity.class);
					startActivityForResult(intent, 1);
					
				}
				break;
			case constantUtil.Num_DelContactByID:
				String result = (String) msg.obj;
				if (result.equals("succeed")) {
					ContactInfoServise ser = new ContactInfoServise(mContext);
					int id1 = msg.arg1;
					ser.DelContactByIDTrue(id1);
					Toast.makeText(mContext, "删除成功！", Toast.LENGTH_SHORT)
							.show();
					finish();

				} else {
					Toast.makeText(getApplication(), "删除失败！",
							Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
		}
	};

	class myThreadById implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer = new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon = conSer
					.SelectContactByID(Integer.parseInt(Lid));
			Message message = new Message();
			message.what = constantUtil.Num_SelectContactByID;
			message.obj = listcon;
			mHandler.sendMessage(message);
		}
	}

	class SelectIdByContactId implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer = new ContactInfoServise(mContext);
			String selectid = conSer.SelectIdByContactId(friendId);
			Message message = new Message();
			message.what = constantUtil.Num_SelectIdByContactId;
			message.obj = selectid;
			mHandler.sendMessage(message);
		}
	}

	class SelectCountByState implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer = new ContactInfoServise(mContext);
			int state = conSer.SelectCountByState();
			Message message = new Message();
			message.what = constantUtil.Num_SelectCountByState;
			message.arg1 = state;
			mHandler.sendMessage(message);
		}
	}

	/*
	 * public class ReceiveBroadCast extends BroadcastReceiver {
	 * 
	 * @Override public void onReceive(Context context, Intent intent) { String
	 * action = intent.getAction(); if (action.equals("lbs_SelectContactByID"))
	 * { // 得到广播中得到的数据，并显示出来 contactInfo = (ContactInfo) intent
	 * .getSerializableExtra("parameter");
	 * 
	 * head_img.setText(contactInfo.get_Name().substring(0, 1));
	 * contact_name.setText(contactInfo.get_Name());
	 * txt_department.setText(contactInfo.get_Department()); if
	 * (contactInfo.get_Sex() == 0) { txt_gender.setText(" 男");
	 * 
	 * } else { txt_gender.setText(" 女"); }
	 * 
	 * txt_national.setText(contactInfo.get_Nationality());
	 * txt_birthday.setText(contactInfo.get_Birthday());
	 * txt_work_address.setText(contactInfo.get_DepartAddress());
	 * txt_home_address.setText(contactInfo.get_Address());
	 * txt_hobby.setText(contactInfo.get_Interest());
	 * txt_preferfoods.setText(contactInfo.get_Food());
	 * 
	 * phonnumbers = contactInfo.get_MobileEn();
	 * 
	 * String[] sourceStrArray = phonnumbers.split(",");// 用，分隔字符串 // 取出单个电话号码
	 * phone.clear(); for (int i = 0; i < sourceStrArray.length; i++) {
	 * 
	 * phone.add(sourceStrArray[i]);
	 * 
	 * } contactPhone.notifyDataSetChanged(); } // 显示联系人朋友 if
	 * (action.equals("V_SelectFriendShip")) { friends.clear(); friends =
	 * (List<V_FriendBean>) intent .getSerializableExtra("parameter"); //
	 * 获取联系人朋友 String fi = ""; for (V_FriendBean contact_friend : friends) { fi
	 * += "  " + contact_friend.get_Name(); } txt_friends.setText(fi); //
	 *  查看更多朋友 txt_friends.setOnClickListener(new OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub Intent intent = new Intent(mContext, FriendsDetailActivity.class);
	 * Bundle bundle = new Bundle(); bundle.putSerializable("friends",
	 * (Serializable) friends); intent.putExtras(bundle);
	 * startActivityForResult(intent, 1); } }); }
	 * 
	 * } }
	 */

	public class ReceiveBroadCast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("DeleteFriendShip")) {
				String result = (String) intent.getSerializableExtra("result");
				if (result.equals("succeed")) {
					Toast.makeText(mContext, "删除成功！！", Toast.LENGTH_SHORT)
							.show();
					childrenData.get(0).remove(postion);
					adapter.notifyDataSetChanged();
				} else {
					Toast.makeText(mContext, "删除失败！！", Toast.LENGTH_SHORT)
							.show();

				}
			}

		}
	}

	class GroupClickListener implements OnGroupClickListener {
		@Override
		public boolean onGroupClick(ExpandableListView parent, View v,
				int groupPosition, long id) {
			if (expandFlag == -1) {
				// 展开被选的group
				explistview.expandGroup(groupPosition);
				// 设置被选中的group置于顶端
				explistview.setSelectedGroup(groupPosition);
				expandFlag = groupPosition;
			} else if (expandFlag == groupPosition) {
				explistview.collapseGroup(expandFlag);
				expandFlag = -1;
			} else {
				explistview.collapseGroup(expandFlag);
				// 展开被选的group
				explistview.expandGroup(groupPosition);
				// 设置被选中的group置于顶端
				explistview.setSelectedGroup(groupPosition);
				expandFlag = groupPosition;
			}
			return true;
		}

	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		init();
		Intent intent = getIntent();

		Lid = intent.getStringExtra("contactID");

		initclick();
		// setLeftText("返回");
		initData();

		setLeftImageBack();

		setViewClick(R.id.tv_title_right_text);// 保存编辑事件
		setRightImage(R.drawable.icon_more, new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final ImageView dddd = (ImageView) findViewById(R.id.iv_title_right_image);
				listitm.clear();
				listitm.add(new Object[] { "编辑", R.drawable.icon_adduser1 });
				listitm.add(new Object[] { "删除", R.drawable.icon_bindphone });

				pop = new PopMenu(PersonalInformationActivity.this,
						R.layout.test, R.id.listv, R.layout.test_itmes,
						listitm, R.id.d1, R.id.ImgVleft, 400);
				pop.showAsDropDown(dddd, -100, 0, true);
				pop.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						switch (arg2) {
						case 0:
							pop.dismiss();
							Intent int_selects = new Intent();
							int_selects.setClass(getApplicationContext(),
									NewContactsActivity.class);
							int_selects.putExtra("actions", "edtcon");
							int_selects.putExtra("conid", Integer.parseInt(Lid));
							Log.i("mt", "编辑" + Lid);
							startActivity(int_selects);
							finish();
							break;
						// 编辑
						case 1:
							pop.dismiss();
							final ContactInfoServise ser = new ContactInfoServise(
									mContext);
							Builder dia = new AlertDialog.Builder(
									PersonalInformationActivity.this)
									.setMessage("是否删除？")
									.setPositiveButton(
											"是",
											new android.content.DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													int state = ser
															.SelectStateByid(Integer
																	.parseInt(Lid));
													if (state == 1) {
														Boolean re = ser
																.DelContactByIDTrue(Integer
																		.parseInt(Lid));
														if (re) {
															Toast.makeText(
																	mContext,
																	"删除成功！",
																	Toast.LENGTH_SHORT)
																	.show();
															PersonalInformationActivity.this
																	.finish();
														} else {
															Toast.makeText(
																	mContext,
																	"删除失败！",
																	Toast.LENGTH_SHORT)
																	.show();
														}
													} else {
														if (NetUtil
																.isNetworkAvailable(mContext)) {
															ContactInfoBLL
																	.DelContactByID(
																			mContext,
																			contactID,
																			Integer.parseInt(Lid),
																			mHandler);

														} else {
															Toast.makeText(
																	mContext,
																	"当前无网络，不能执行删除！",
																	Toast.LENGTH_SHORT)
																	.show();
														}
													}
												}
											})
									.setNegativeButton(
											"否",
											new android.content.DialogInterface.OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											});
							dia.show();

							break;
						// 删除

						default:
							break;
						}
					}
				});
			}
		});

		contactPhone = new CommonAdapter<String>(
				PersonalInformationActivity.this, phone,
				R.layout.item_personal_phone) {

			@Override
			public void convert(ViewHolder holder, String t) {
				// TODO Auto-generated method stub
				holder.setText(R.id.contact_phone, t);
				final String phoneNumber = t;
				// 打电话
				holder.setOnClickListener(R.id.imageViewCall,
						new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								Intent dialIntent = new Intent(
										Intent.ACTION_DIAL, Uri.parse("tel:"
												+ phoneNumber));// 跳转到拨号界面，同时传递电话号码
								startActivity(dialIntent);
							}
						});
				// 发短信
				holder.setOnClickListener(R.id.imageViewSsm,
						new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								Uri smsToUri = Uri
										.parse("smsto:" + phoneNumber);
								Intent intent = new Intent(
										Intent.ACTION_SENDTO, smsToUri);
								startActivity(intent);
							}
						});
			}

		};

		phonenumber.setAdapter(contactPhone);

		ReceiveBroadCast receiveBroadCast = new ReceiveBroadCast();
		IntentFilter filter = new IntentFilter();
		filter.addAction("DeleteFriendShip");
		registerReceiver(receiveBroadCast, filter);

		// 联系人
		if (Lid != null) {
			// 查询数据
			new Thread(new myThreadById()).start();

			Log.i("mt", Lid + "id+++PersonalInformation");

		}

	}

	@Override
	public void OnViewClick(View v) {
		switch (v.getId()) {
		case R.id.add_friends:// 添加朋友

			if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
				Toast.makeText(PersonalInformationActivity.this,
						"亲，您当前处于无网络状态！", Toast.LENGTH_SHORT).show();
			} else {
				// 查询本地有无更改

				new Thread(new SelectCountByState()).start();

			}

			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		// ContactInfoBLL.SelectContactByID(mContext, contactID);
		// FriendshipBLL.SelectFriendShipView(mContext, contactID);
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		FriendshipBLL.SelectFriendShipViewmt(mContext, contactID,
				mHandler);
	}

}

/****************************************/
/*
 * public class lv_phone extends ListView {
 * 
 * public lv_phone (Context context) { super(context); }
 * 
 * public lv_phone (Context context, AttributeSet attrs) { super(context,
 * attrs); }
 * 
 * public lv_phone (Context context, AttributeSet attrs, int defStyle) {
 * super(context, attrs, defStyle); }
 * 
 * @Override protected void onMeasure(int widthMeasureSpec, int
 * heightMeasureSpec) { int expandSpec =
 * MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
 * super.onMeasure(widthMeasureSpec, expandSpec); } }
 */

